package com.aisino.mvpdesignproject2.ui.presenter;

import com.aisino.mvpdesignproject2.constant.AppConstants;
import com.aisino.mvpdesignproject2.http.itf.Stateful;
import com.aisino.mvpdesignproject2.http.rxjava.BaseObserver;
import com.aisino.mvpdesignproject2.http.rxjava.BaseSubscriptionHelper;
import com.aisino.mvpdesignproject2.http.uitl.HttpUtils;
import com.aisino.mvpdesignproject2.ui.contract.BaseContract;
import com.aisino.mvpdesignproject2.ui.model.BaseModel;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class BasePresenter implements BaseContract.Presenter, BaseSubscriptionHelper {
    private CompositeDisposable mDisposables;
    private Stateful stateful;
    private BaseContract.View view;
    private BaseModel model;

    public BasePresenter() {
    }

    public BasePresenter(BaseContract.View view) {
        this.view = view;
        this.model = new BaseModel();
    }

    public void setStateful(Stateful stateful) {
        this.stateful = stateful;
    }

    protected <T> void invoke(Observable<T> observable, BaseObserver<T> callback) {
        HttpUtils.invoke(stateful, observable, callback);
    }

    /**
     * 给子类检查返回集合是否为空
     * 这样子做虽然耦合度高，但是接口都不是统一定的，我们没有什么更好的办法
     *
     * @param list
     * @param isEmpty 如果是不是第一页但是后面页没数据
     */
    public void checkState(List list, boolean isEmpty) {
        if (isEmpty) {
            if (null == list || list.size() == 0) {
                stateful.setState(AppConstants.STATE_EMPTY);

                return;
            } else {
                stateful.setState(AppConstants.STATE_SUCCESS);

                return;
            }
        } else {
            stateful.setState(AppConstants.STATE_SUCCESS);

            return;
        }

    }

    @Override
    public void add(Disposable disposable) {
        if (mDisposables == null) {
            mDisposables = new CompositeDisposable();
        }
        mDisposables.add(disposable);
    }

    @Override
    public void cancle(Disposable disposable) {
        if (mDisposables != null) {
            mDisposables.delete(disposable);
        }
    }

    @Override
    public void cancleAll() {
        if (mDisposables != null) {
            mDisposables.clear();
        }
    }

    @Override
    public <T> void onSuccess(T t) {
        view.loadSuccess(t);
    }

    @Override
    public void onFail(String msg) {
        view.loadFail(msg);
    }
}
